<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['invoice:invoice_template:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['invoice:invoice_template:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['invoice:invoice_template:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['invoice:invoice_template:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="invoice_templateList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="templateId" />
      <el-table-column label="模版编码" align="center" prop="stencilCoding" />
      <el-table-column label="模版名称" align="center" prop="templateName" />
      <el-table-column
        label="借方科目名称"
        align="center"
        prop="lendSubjectName"
      />
      <el-table-column
        label="贷方科目名称"
        align="center"
        prop="loanSubjectName"
      />
      <el-table-column label="摘要名称" align="center" prop="summaryName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['invoice:invoice_template:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['invoice:invoice_template:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handPreview(scope.row.templateId)"
            v-hasPermi="['invoice:invoice_template:remove']"
            >预览</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改发票凭证模版对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form
        ref="invoice_templateRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          
          <el-col :span="12">
            <el-form-item label="模版名称" prop="templateName">
              <el-input
                v-model="form.templateName"
                placeholder="请输入模版名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="凭证字" prop="wordId">
              <el-select
                v-model="form.wordId"
                placeholder="请选择凭证字"
                style="width: 100%"
              >
                <el-option
                  v-for="item in voucherWordOptions"
                  :key="item.wordId"
                  :label="item.wordName"
                  :value="item.wordId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="businessTypeId">
              <el-select
                v-model="form.businessTypeId"
                placeholder="请选择业务类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in businessTypeOptions"
                  :key="item.businessTypeId"
                  :label="item.businessTypeName"
                  :value="item.businessTypeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 表格式输入界面 -->
        <el-table
          :data="form.entries"
          border
          style="width: 100%; margin-top: 15px"
        >
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />
          <el-table-column label="摘要" align="center">
            <template #default="scope">
              <el-select
                v-model="scope.row.summaryId"
                placeholder="请选择摘要"
                style="width: 100%"
              >
                <el-option
                  v-for="item in summaryOptions"
                  :key="item.summaryId"
                  :label="item.summaryContent"
                  :value="item.summaryId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="会计科目" align="center">
            <template #default="scope">
              <el-select
                v-model="scope.row.subjectId"
                placeholder="请选择会计科目"
                style="width: 100%"
              >
                <el-option
                  v-for="item in subjectOptions"
                  :key="item.subjectId"
                  :label="item.subjectName"
                  :value="item.subjectId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="方向" width="100" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.direction" style="width: 100%">
                <el-option label="借" value="0" />
                <el-option label="贷" value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="取值" width="180" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.valueType" style="width: 100%">
                <el-option label="不含税金额" value="0" />
                <el-option label="含税金额" value="1" />
                <el-option label="价税合计" value="2" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button link type="primary" icon="Plus" @click="handleAddRow"
                >添加</el-button
              >
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDeleteRow(scope.$index)"
                :disabled="form.entries.length <= 1"
                >移除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 预览发票凭证明细弹窗 -->
    <el-dialog :title="'预览凭证模板'" v-model="previewOpen" width="800px" append-to-body>
      <el-table :data="previewData" border style="width: 100%; margin-top: 15px">
        <el-table-column label="摘要" prop="summaryContent" align="center" />
        <el-table-column label="会计科目" prop="subjectName" align="center" />
        <el-table-column label="借方" prop="debitAmount" align="center" >
          <template #default="scope">
            <el-input-number
              v-if="scope.row.direction === 0"
              v-model="scope.row.amount"
              :min="0"
              :step="0.01"
              controls-position="right"
            />
          </template>
        </el-table-column>
        <el-table-column label="贷方" prop="creditAmount" align="center" >
          <template #default="scope">
            <el-input-number
              v-if="scope.row.direction === 1"
              v-model="scope.row.amount"
              :min="0"
              :step="0.01"
              controls-position="right"
            />
          </template>
        </el-table-column>
      </el-table>
       <!-- 合计行 -->
      <div style="text-align: right; margin-top: 10px;">
        <span>借方合计: {{ totalDebit }}</span>
        <span style="margin-left: 20px;">贷方合计: {{ totalCredit }}</span>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>

<script setup name="Invoice_template">
import {
  listInvoice_template,
  getInvoice_template,
  delInvoice_template,
  addInvoice_template,
  updateInvoice_template,
  getSelectAll,
  getTemplateDetail,
} from "@/api/invoice/invoice_template";

const { proxy } = getCurrentInstance();

const invoice_templateList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");



const data = reactive({
  form: {
    entries: [], // 初始化表格数据
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    templateName: [
      { required: true, message: "模版名称不能为空", trigger: "blur" },
    ],
    wordId: [{ required: true, message: "凭证字不能为空", trigger: "change" }],
    businessTypeId: [
      { required: true, message: "业务类型不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);


// 下拉选项数据
const voucherWordOptions = ref([]); // 凭证字选项
const businessTypeOptions = ref([]); // 业务类型选项
const subjectOptions = ref([]); // 会计科目选项
const summaryOptions = ref([]);


function getSelectAllData() {
  getSelectAll().then((response) => {
    voucherWordOptions.value = response.data.wordList;
    businessTypeOptions.value = response.data.businessTypeList;
    subjectOptions.value = response.data.subjectList;
    summaryOptions.value = response.data.summaryList;
  });
}


/** 查询发票凭证模版列表 */
function getList() {
  loading.value = true;
  listInvoice_template(queryParams.value).then((response) => {
    invoice_templateList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}





// 添加表格行
function handleAddRow() {
  form.value.entries.push({
    summaryId: "",
    subjectId: null,
    direction: "0",
    valueType: "1",
  });
}

// 删除表格行
function handleDeleteRow(index) {
  form.value.entries.splice(index, 1);
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    templateId: null,
    stencilCoding: null,
    templateName: null,
    wordId: null,
    businessTypeId: null,
    lendSubjectName: null,
    loanSubjectName: null,
    summaryName: null,
    entries: [
      {
        // 初始化一行数据
        summaryId: "",
        subjectId: null,
        direction: "0",
        valueType: "1",
      },
    ],
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
  };
  proxy.resetForm("invoice_templateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.templateId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getSelectAllData();
  open.value = true;
  title.value = "添加发票凭证模版";
}

/** 修改按钮操作 */
// function handleUpdate(row) {
//   reset();
//   getSelectAllData();
//   const _templateId = row.templateId || ids.value;
//   getInvoice_template(_templateId).then((response) => {
//     form.value = response.data;
//     // 如果后端返回的数据中没有entries，则初始化一个
//     if (!form.value.entries || !form.value.entries.length) {
//       form.value.entries = [
//         {
//           summaryId: "",
//           subjectId: null,
//           direction: "",
//           valueType: "",
//         },
//       ];
//     }
//     open.value = true;
//     title.value = "修改发票凭证模版";
//   });
// }

function handleUpdate(row) {
  reset();
  getSelectAllData();
  const _templateId = row.templateId || ids.value;
  getInvoice_template(_templateId).then((response) => {
    form.value = response.data;
    // 如果后端返回的数据中没有entries，则初始化一个
    if (!form.value.entries || !form.value.entries.length) {
      form.value.entries = [
        {
          summaryId: "",
          subjectId: null,
          direction: "0",
          valueType: "",
        },
      ];
    } else {
      // 确保direction和valueType是字符串类型
      form.value.entries.forEach(entry => {
        entry.direction = entry.direction.toString();
        entry.valueType = entry.valueType.toString();
      });
    }
    open.value = true;
    title.value = "修改发票凭证模版";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["invoice_templateRef"].validate((valid) => {
    if (valid) {
      // 处理表单数据，将表格数据转换为后端需要的格式
      const submitData = { ...form.value };

      if (form.value.templateId != null) {
        updateInvoice_template(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInvoice_template(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _templateIds = row.templateId || ids.value;
  proxy.$modal
    .confirm('是否确认删除发票凭证模版编号为"' + _templateIds + '"的数据项？')
    .then(function () {
      return delInvoice_template(_templateIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "invoice/invoice_template/export",
    {
      ...queryParams.value,
    },
    `invoice_template_${new Date().getTime()}.xlsx`
  );
}

getList();


// 添加预览相关的数据
const previewOpen = ref(false);
const previewData = ref([])

// ... existing code ...

/** 预览 */
function handPreview(templateId) {
  getTemplateDetail(templateId).then((response) => {
    previewData.value = response.data;
    previewOpen.value = true;
  });
}

// 添加合计相关的数据
const totalDebit = computed(() => {
  return previewData.value.reduce((sum, entry) => {
    return sum + (entry.direction === 0 ? parseFloat(entry.amount) : 0);
  }, 0).toFixed(2);
});
const totalCredit = computed(() => {
  return previewData.value.reduce((sum, entry) => {
    return sum + (entry.direction === 1 ? parseFloat(entry.amount) : 0);
  }, 0).toFixed(2);
});


</script>
